package com.fzg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fzg.common.enums.ResponseWrapper;
import com.fzg.common.model.enterprise.param.*;
import com.fzg.common.model.enterprise.result.*;
import com.fzg.common.tool.MD5Tool;
import com.fzg.common.tool.ToolForDateTime;
import com.fzg.entity.CompanyEvaluate;
import com.fzg.entity.Enterprise;
import com.fzg.entity.RecruitmentEnterprise;
import com.fzg.entity.User;
import com.fzg.mapper.CompanyEvaluateMapper;
import com.fzg.mapper.EnterpriseMapper;
import com.fzg.mapper.RecruitmentEnterpriseMapper;
import com.fzg.mapper.UserMapper;
import com.fzg.service.EnterpriseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import static com.fzg.common.tool.ToolForDateTime.LocalDateTimeToStringToDate;
import static com.fzg.common.tool.ToolForDateTime.StringDateToYearMonthDay;

/**
 * <p>
 * 企业表 服务实现类
 * </p>
 *
 * @author fzg
 * @since 2021-12-13
 */
@Service
public class EnterpriseServiceImpl extends ServiceImpl<EnterpriseMapper, Enterprise> implements EnterpriseService {

    @Autowired
    private EnterpriseMapper enterpriseMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CompanyEvaluateMapper companyEvaluateMapper;

    @Autowired
    private RecruitmentEnterpriseMapper recruitmentEnterpriseMapper;

    @Override
    public ResponseWrapper getEnterpriseList(GetEnterpriseListParam param) {
        // 返回结果
        GetEnterpriseListResult result = new GetEnterpriseListResult();

        Page<Enterprise> enterprisePage = null;

        if (param.getAccount() != null && param.getName() == null){
            // 账号不为空，名称为空
            enterprisePage = enterpriseMapper.selectPage(
                    new Page<>(param.getPage(),param.getPageRow()),
                    new LambdaQueryWrapper<Enterprise>()
                        .like(Enterprise::getAccountNumber,param.getAccount())
                        .orderByDesc(Enterprise::getCreateTime)
            );
        }
        if (param.getAccount() == null && param.getName() != null){
            // 账号为空，名称不为空
            enterprisePage = enterpriseMapper.selectPage(
                    new Page<>(param.getPage(),param.getPageRow()),
                    new LambdaQueryWrapper<Enterprise>()
                        .like(Enterprise::getName,param.getName())
                        .orderByDesc(Enterprise::getCreateTime)
            );
        }
        if (param.getAccount() != null && param.getName() != null){
            // 账号不为空，名称不为空
            enterprisePage = enterpriseMapper.selectPage(
                    new Page<>(param.getPage(),param.getPageRow()),
                    new LambdaQueryWrapper<Enterprise>()
                            .like(Enterprise::getName,param.getName())
                            .like(Enterprise::getAccountNumber,param.getAccount())
                            .orderByDesc(Enterprise::getCreateTime)
            );
        }
        if (enterprisePage == null){
            return ResponseWrapper.markCustomError("查询失败！");
        }else {
            result.setTotalNum((int)enterprisePage.getTotal());
            ArrayList<GetEnterpriseListResultItem> enterpriseList = new ArrayList<>();
            for (Enterprise enterprise : enterprisePage.getRecords()) {
                GetEnterpriseListResultItem item = new GetEnterpriseListResultItem();
                item.setAid(enterprise.getAid());
                item.setName(enterprise.getName());
                item.setAccount(enterprise.getAccountNumber());
                item.setLeader(enterprise.getLeader());
                item.setPhone(enterprise.getPhone());
                item.setEmail(enterprise.getEmail());
                item.setAddress(enterprise.getAddress());
                item.setCreateTime(StringDateToYearMonthDay(LocalDateTimeToStringToDate(enterprise.getCreateTime())));
                item.setEnterpriseAvatar(enterprise.getAvatar());
                item.setIntroduction(enterprise.getIntroduction());
                item.setEnterpriseBgImage(enterprise.getBgImage());
                item.setEmployeeCount(enterprise.getEmployeeCount());
                enterpriseList.add(item);
            }
            result.setEnterpriseList(enterpriseList);
            return ResponseWrapper.markSuccess(result);
        }
    }

    /**
     * 获取企业列表(前端展示所有企业)
     *
     * @return ResponseWrapper
     */
    @Override
    public ResponseWrapper getCompanyList() {

        GetCompanyListAndRecruitCount result = new GetCompanyListAndRecruitCount();

        List<Enterprise> enterprises = enterpriseMapper.selectList(new LambdaQueryWrapper<Enterprise>()
            .orderByDesc(Enterprise::getCreateTime)
            .last("limit 20"));
        result.setCompanyList(enterprises);

        List<RecruitmentEnterprise> recruitmentEnterprises = recruitmentEnterpriseMapper.selectList(null);
        result.setTotalposCount(recruitmentEnterprises.size());

        return ResponseWrapper.markSuccess(result);
    }

    @Override
    public ResponseWrapper checkAccount(CheckAccountParam param) {

        // 返回结果
        CheckEnterpriseAccountResult result = new CheckEnterpriseAccountResult();

        if (param.getAid().equals(-1)){
            // 新增时判断account是否存在相同的
            Enterprise enterprise = enterpriseMapper.selectOne(new LambdaQueryWrapper<Enterprise>().eq(Enterprise::getAccountNumber, param.getAccount()));
            // 存在相同的account
            result.setIsExist(enterprise != null);
        }else {
            // 修改时，判断account是否存在相同的同时排除自身account
            Enterprise enterprise = enterpriseMapper.selectOne(new LambdaQueryWrapper<Enterprise>()
                    .ne(Enterprise::getAid,param.getAid())
                    .eq(Enterprise::getAccountNumber, param.getAccount()));
            // 存在相同的account
            result.setIsExist(enterprise != null);
        }
        return ResponseWrapper.markSuccess(result);
    }

    @Override
    public ResponseWrapper checkPhone(CheckEnterprisePhoneParam param) {

        // 返回结果
        CheckEnterprisePhoneResult result = new CheckEnterprisePhoneResult();

        if (param.getAid().equals(-1)){
            // 添加企业时，直接判断企业联系电话是否相同
            Enterprise enterprise = enterpriseMapper.selectOne(new LambdaQueryWrapper<Enterprise>().eq(Enterprise::getPhone, param.getPhone()));
            // 存在相同手机号
            result.setIsExist(enterprise != null);
        }else {
            // 编辑企业时，排除自身企业aid的phone。
            Enterprise enterprise = enterpriseMapper.selectOne(new LambdaQueryWrapper<Enterprise>().ne(Enterprise::getAid, param.getAid())
                    .eq(Enterprise::getPhone, param.getPhone()));
            result.setIsExist(enterprise != null);
        }
        return ResponseWrapper.markSuccess(result);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper addOrEditEnterprise(AddOrEditEnterpriseParam param) {
        if (param.getAid().equals(-1)){
            // 添加企业
            Enterprise enterprise = enterpriseMapper.selectOne(new LambdaQueryWrapper<Enterprise>().orderByDesc(Enterprise::getAid).last("limit 1"));
            int insert = enterpriseMapper.insert(new Enterprise() {{
                setAid(enterprise.getAid() + 1);
                setName(param.getName());
                setAccountNumber(param.getAccount());
                setPhone(param.getPhone());
                setAddress(param.getAddress());
                setLeader(param.getLeader());
                setPassword(MD5Tool.getMD5("123456"));
                setEmail(param.getEmail());
            }});
            if (insert > 0 ){
                return ResponseWrapper.markCustomSuccess("添加成功！");
            }else {
                return ResponseWrapper.markCustomError("添加失败！");
            }
        }else {
            // 修改企业
            int update = enterpriseMapper.update(new Enterprise() {{
                setName(param.getName());
                setAccountNumber(param.getAccount());
                setPhone(param.getPhone());
                setAddress(param.getAddress());
                setLeader(param.getLeader());
                setEmail(param.getEmail());
            }}, new LambdaUpdateWrapper<Enterprise>().eq(Enterprise::getAid, param.getAid()));
            if (update > 0){
                return ResponseWrapper.markCustomSuccess("修改成功！");
            }else {
                return ResponseWrapper.markCustomError("修改失败！");
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper delEnterprise(DelEnterpriseParam param) {
        int delete = enterpriseMapper.deleteById(param.getAid());
        if (delete > 0){
            return ResponseWrapper.markCustomError("删除成功！");
        }else {
            return ResponseWrapper.markCustomError("删除失败！");
        }
    }

    @Override
    public ResponseWrapper getCompanyInfoByAccount(GetCompanyInfoByAccountParam param) {
        Enterprise enterprise = enterpriseMapper.selectOne(new LambdaQueryWrapper<Enterprise>().eq(Enterprise::getAccountNumber, param.getAccount()));
        if (enterprise!=null){
            GetCompanyInfoByAccountResult result = new GetCompanyInfoByAccountResult();
            result.setAid(enterprise.getAid());
            result.setAvatar(enterprise.getAvatar());
            result.setIntroduction(enterprise.getIntroduction());
            result.setBgImage(enterprise.getBgImage());
            result.setEmployeeCount(enterprise.getEmployeeCount());
            result.setAccount(enterprise.getAccountNumber());
            result.setName(enterprise.getName());
            result.setLeader(enterprise.getLeader());
            result.setPhone(enterprise.getPhone());
            result.setEmail(enterprise.getEmail());
            result.setCreateTime(StringDateToYearMonthDay(LocalDateTimeToStringToDate(enterprise.getCreateTime())));
            result.setAddress(enterprise.getAddress());
            return ResponseWrapper.markSuccess(result);
        }else {
            return ResponseWrapper.markCustomError("企业信息获取失败！");
        }
    }

    /**
     * 获取所有企业
     */
    @Override
    public ResponseWrapper getAllCompany() {
        ArrayList<Enterprise> result = new ArrayList<>();
        List<Enterprise> enterprises = enterpriseMapper.selectList(null);
        if (enterprises.size()>0){
            return ResponseWrapper.markSuccess(enterprises);
        }else {
            return ResponseWrapper.markSuccess(result);
        }

    }

    /**
     * 当前登陆的企业修改自己信息
     *
     * @param param 参数类
     */
    @Override
    public ResponseWrapper updateCompanyInfo(UpdateCompanyInfoParam param) {
        // 通过账号查询当前登陆的企业
        Enterprise enterprise = enterpriseMapper.selectOne(new LambdaQueryWrapper<Enterprise>().eq(Enterprise::getAccountNumber, param.getAccount()));
        Enterprise enterprise1 = new Enterprise();
        enterprise1.setAid(enterprise.getAid());
        enterprise1.setAccountNumber(enterprise.getAccountNumber());
        enterprise1.setName(param.getName());
        enterprise1.setPassword(enterprise.getPassword());
        enterprise1.setLeader(param.getLeader());
        enterprise1.setPhone(param.getPhone());
        enterprise1.setEmail(param.getEmail());
        enterprise1.setAddress(param.getAddress());
        if (param.getAvatar().equals("")){
            enterprise1.setAvatar("");
        }else {
            enterprise1.setAvatar(param.getAvatar());
        }
        if (param.getBgImage().equals("")){
            enterprise1.setBgImage("");
        }else {
            enterprise1.setBgImage(param.getBgImage());
        }
        if (param.getIntroduction().equals("")){
            enterprise1.setIntroduction("");
        }else {
            enterprise1.setIntroduction(param.getIntroduction());
        }
        int updateById = enterpriseMapper.updateById(enterprise1);
        if (updateById > 0){
            return ResponseWrapper.markCustomSuccess("修改成功！");
        }else {
            return ResponseWrapper.markCustomError("修改失败！");
        }
    }

    /**
     * 检验当前登陆企业修改的企业联系电话是否已经存在
     *
     * @param param 参数类
     */
    @Override
    public ResponseWrapper checkPhoneExistApi(CheckPhoneExistApiParam param) {
        // 查询用户表
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getPhone, param.getPhone()));
        if (user != null){
            return ResponseWrapper.markSuccess(true);
        }else {
            // 查询企业表
            Enterprise enterprise = enterpriseMapper.selectOne(new LambdaQueryWrapper<Enterprise>()
                    .ne(Enterprise::getAccountNumber,param.getAccount())
                    .eq(Enterprise::getPhone, param.getPhone()));
            if (enterprise != null){
                return ResponseWrapper.markSuccess(true);
            }else {
                return ResponseWrapper.markSuccess(false);
            }
        }
    }

    /**
     * 获取公司的评价列表
     *
     * @param param 参数类
     */
    @Override
    public ResponseWrapper getCompanyEvaluateList(GetCompanyEvaluateListParam param) {
        Enterprise enterprise = enterpriseMapper.selectOne(new LambdaQueryWrapper<Enterprise>().eq(Enterprise::getAccountNumber, param.getAccount()));
        List<CompanyEvaluate> evaluateList = companyEvaluateMapper.selectList(new LambdaQueryWrapper<CompanyEvaluate>().eq(CompanyEvaluate::getEnterpriseAid, enterprise.getAid()));

        ArrayList<CompanyEvaluateResult> result = new ArrayList<>();
        for (CompanyEvaluate item : evaluateList) {
            CompanyEvaluateResult evaluation = new CompanyEvaluateResult();
            evaluation.setAid(item.getAid());
            evaluation.setEnterpriseAid(item.getEnterpriseAid());
            evaluation.setContent(item.getContent());
            evaluation.setCreateTime(ToolForDateTime.LocalDateTimeToString(item.getCreateTime()));
            evaluation.setUpdateTime(ToolForDateTime.LocalDateTimeToString(item.getUpdateTime()));
            result.add(evaluation);
        }

        return ResponseWrapper.markSuccess(result);
    }

    /**
     * 提交评论
     *
     * @param param 参数类
     */
    @Override
    public ResponseWrapper submitEvaluation(SubmitEvaluationParam param) {
        Enterprise enterprise = enterpriseMapper.selectOne(new LambdaQueryWrapper<Enterprise>().eq(Enterprise::getAccountNumber, param.getAccount()));
        CompanyEvaluate companyEvaluate = new CompanyEvaluate();
        companyEvaluate.setEnterpriseAid(enterprise.getAid());
        companyEvaluate.setContent(param.getContent());
        int insert = companyEvaluateMapper.insert(companyEvaluate);
        if (insert > 0){
            return ResponseWrapper.markCustomSuccess("评论发表成功！");
        }else {
            return ResponseWrapper.markCustomError("评论发表失败！");
        }
    }
}
